import { useEffect, useState, CSSProperties, ChangeEvent } from "react";
import { Pen } from "@meta2d/core";
import { FileImageOutlined, FolderOutlined } from "@ant-design/icons";
import styles from "@/layout/Layout.module.scss";
import { Button, Divider, Drawer, Input, Space } from "antd";
export function PensSelection({
  open,
  onOk,
  onClose,
  value,
}: {
  onOk: (id: string) => void;
  open: boolean;
  onClose: () => void;
  value: string;
}) {
  const [pens, setPens] = useState<Pen[]>([]);
  const [choosePenId, setChoosePenId] = useState(value);
  const [targetTag, setTargetTag] = useState<string>("");
  const activePen = (id: string) => {
    setChoosePenId(() => id);
    setTargetTag(() => "");
    //pen的视图定位
    let targetPen = window.meta2d.findOne(id);
    if (targetPen != undefined) {
      window.meta2d.gotoView(targetPen);
    }
  };
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setTargetTag(() => e.target.value);
    if (choosePenId != "") {
      setChoosePenId(() => "");
    }
  };
  let iconStyle: CSSProperties = {
    marginRight: 5,
    fontSize: 14,
  };
  const onClickOk = () => {
    if (targetTag != "") {
      onOk(targetTag);
    } else {
      onOk(choosePenId);
    }
  };
  useEffect(() => {
    setPens(() => window.meta2d.store.data.pens);
  }, []);

  return (
    <>
      <Drawer
        title="选择目标图元"
        placement="right"
        onClose={onClose}
        open={open}
        extra={
          <Space>
            <Button type="primary" size={"small"} onClick={onClickOk}>
              确定
            </Button>
          </Space>
        }
      >
        <Divider orientation="left" plain>
          指定Tag
        </Divider>
        <Input
          placeholder={"目标图元，你要更改属性的图元的tag"}
          value={targetTag}
          onChange={handleChange}
        ></Input>
        <Divider orientation="left" plain>
          指定Id
        </Divider>
        {pens.map((item) => (
          <div
            key={item.id}
            className={styles.PensSelection}
            onClick={() => {
              activePen(item.id as string);
            }}
            style={{ color: choosePenId == item.id ? "#1890ff" : "#fff" }}
          >
            <span style={iconStyle}>
              {item.children && item.children.length > 0 ? (
                <FolderOutlined />
              ) : (
                <FileImageOutlined />
              )}
            </span>
            {item.id}
            {item.description && (
              <span style={{ marginLeft: 5 }}>({item.description})</span>
            )}
          </div>
        ))}
      </Drawer>
    </>
  );
}
